<template>
  <div class="login">
    <el-form :model="form" :rules="rules" ref="form" label-width="80px" status-icon>
      <img class="belle" src="../assets/01.jpg" alt />
      <el-form-item label="用户名" label-width="80px" prop="username">
        <el-input placeholder="请输入用户名" v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="login" class="elBtn" type="primary">登录</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          {
            required: true,
            message: '请输入用户名称',
            trigger: ['blur', 'change']
          },
          {
            min: 3,
            max: 5,
            message: '长度在 3 到 5 个字符',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['blur', 'change']
          },
          {
            min: 3,
            max: 12,
            message: '长度在 3 到 12 个字符',
            trigger: ['blur', 'change']
          }
        ]
      }
    }
  },
  methods: {
    reset () {
      this.$refs.form.resetFields()
    },
    async login () {
      try {
        await this.$refs.form.validate()

        const { meta, data } = await this.$axios.post('login', this.form)
        if (meta.status === 200) {
          this.$message({
            showClose: true,
            message: meta.msg,
            type: 'success',
            duration: 2000
          })

          // 将token字符串存到localStorage中去
          localStorage.setItem('token', data.token)

          this.$router.push('/index')
        } else {
          this.$message({
            showClose: true, // 配置可以手动关闭
            message: meta.msg,
            type: 'error',
            duration: 2000
          })
        }
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

<style lang="less" scopet>
.login {
  background-color: #2d434c;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .el-form {
    width: 400px;
    background-color: #fff;
    margin: 0 auto;
    margin-top: 200px;
    padding: 75px 20px 20px;
    border-radius: 20px;
    position: relative;

    .elBtn {
      margin-right: 70px;
    }
    .belle {
      width: 100px;
      height: 120px;
      position: absolute;
      top: -75px;
      left: 50%;
      transform: translate(-50%);
      border: 5px solid #fff;
      border-radius: 50%;
    }
  }
}
</style>
